package com.lzw.breezeNovel.webApp.service.impl.video;

import com.lzw.breezeNovel.common.exception.BaseException;
import com.lzw.breezeNovel.common.login.LoginUser;
import com.lzw.breezeNovel.common.login.LoginUserHolder;
import com.lzw.breezeNovel.common.result.ResultCodeEnum;
import com.lzw.breezeNovel.model.entity.pojo.user.UserInfo;
import com.lzw.breezeNovel.model.entity.pojo.video.Danmu;
import com.lzw.breezeNovel.webApp.mapper.user.UserInfoMapper;
import com.lzw.breezeNovel.webApp.mapper.video.DanmuMapper;
import com.lzw.breezeNovel.webApp.service.video.DanmuService;
import com.lzw.breezeNovel.webApp.vo.video.DanmuVo;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

import static java.util.stream.Collectors.toList;

/**
 * @author 清风明月
 * @Package com.lzw.breezeNovel.webApp.service.impl.video
 * @date 2025/3/19
 * @description 弹幕
 */
@Service
@SuppressWarnings("all")
public class DanmuServiceImpl implements DanmuService {

    /**
     * 注入用户mapper
     */
    @Autowired
    private UserInfoMapper userMapper;

    /**
     * 注入mapper
     */
    @Autowired
    private DanmuMapper danmuMapper;

    /**
     * 获取弹幕
     *
     * @param videoId
     * @param type
     * @param episodes
     * @return
     */
    @Override
    @Transactional(readOnly = true)
    public List<DanmuVo> getDanmu(Integer videoId, Integer type, Integer episodes) {
        //获取当前用户
        Long userId = getCurrentUser();
        //获取弹幕
        List<Danmu> danmus = danmuMapper.selectByVideoIdAndUserId(Long.valueOf(videoId), userId, Long.valueOf(type),episodes);
        //循环遍历对数据进行拷贝
        return danmus.stream().map(danmu -> {
            DanmuVo danmuVo = new DanmuVo();
            BeanUtils.copyProperties(danmu, danmuVo);
            return danmuVo;
        }).collect(toList());
    }

    /**
     * 添加弹幕
     * @param danmu
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addDanmu(@NotNull Danmu danmu) {
        //获取当前用户
        Long userId = getCurrentUser();
        //添加弹幕
        danmu.setUserId(userId);
        danmuMapper.insert(danmu);
    }

    /**
     * 获取当前用户
     * @return
     */
    @Nullable
    private Long getCurrentUser() {
        LoginUser loginUser = LoginUserHolder.getLoginUser();
        //判断用户是否登录
        if (loginUser == null) {
            throw new BaseException(ResultCodeEnum.APP_LOGIN_AUTH);
        }
        //获取用户信息
        String phone = loginUser.getPhone();
        UserInfo userInfo = userMapper.selectByPhone(phone);
        return userInfo.getUserId();
    }
}
